/**
 * 币安交易对状态监控服务
 * 专门监控USDT合约交易对的status状态变化
 * 当状态从TRADING变为BREAK时发送告警
 */

const axios = require('axios');
const logger = require('../utils/logger');

class BinanceStatusService {
  constructor() {
    this.baseURL = 'https://api.binance.com';
    this.futuresURL = 'https://fapi.binance.com';
    this.retryCount = 3;
    this.retryDelay = 2000;
    this.previousStatus = new Map(); // 存储上一次的状态
  }

  /**
   * 检查API连接状态
   * @returns {Promise<boolean>} 连接状态
   */
  async checkConnection() {
    try {
      logger.info('检查币安状态监控API连接...');
      const response = await axios.get(`${this.baseURL}/api/v3/ping`, {
        timeout: 5000
      });
      
      if (response.status === 200) {
        logger.success('✅ 币安状态监控API连接正常');
        return true;
      }
      return false;
    } catch (error) {
      logger.warn(`⚠️  币安状态监控API连接失败: ${error.message}`);
      return false;
    }
  }

  /**
   * 获取现货交易对状态信息
   * @returns {Promise<Array>} 交易对状态数组
   */
  async fetchSpotExchangeInfo() {
    for (let attempt = 1; attempt <= this.retryCount; attempt++) {
      try {
        logger.debug(`正在获取币安现货交易对状态... (尝试 ${attempt}/${this.retryCount})`);
        
        const response = await axios.get(`${this.baseURL}/api/v3/exchangeInfo`, {
          timeout: 15000,
          headers: {
            'User-Agent': 'Binance-Status-Monitor/1.0.0'
          }
        });

        if (response.data && response.data.symbols) {
          const usdtSymbols = response.data.symbols.filter(symbol => 
            symbol.symbol.endsWith('USDT') && 
            symbol.status // 确保有status字段
          );
          
          logger.debug(`获取到 ${usdtSymbols.length} 个USDT现货交易对状态`);
          return usdtSymbols.map(symbol => ({
            symbol: symbol.symbol,
            status: symbol.status,
            type: 'SPOT'
          }));
        }

        logger.warn('响应数据格式异常，无symbols字段');
        return [];

      } catch (error) {
        logger.error(`币安现货API请求失败 (尝试 ${attempt}/${this.retryCount}): ${error.message}`);
        
        if (attempt < this.retryCount) {
          logger.info(`等待 ${this.retryDelay}ms 后重试...`);
          await new Promise(resolve => setTimeout(resolve, this.retryDelay));
        }
      }
    }

    logger.error('所有重试失败，无法获取币安现货交易对状态');
    return [];
  }

  /**
   * 获取期货交易对状态信息
   * @returns {Promise<Array>} 期货交易对状态数组
   */
  async fetchFuturesExchangeInfo() {
    for (let attempt = 1; attempt <= this.retryCount; attempt++) {
      try {
        logger.debug(`正在获取币安期货交易对状态... (尝试 ${attempt}/${this.retryCount})`);
        
        const response = await axios.get(`${this.futuresURL}/fapi/v1/exchangeInfo`, {
          timeout: 15000,
          headers: {
            'User-Agent': 'Binance-Status-Monitor/1.0.0'
          }
        });

        if (response.data && response.data.symbols) {
          const usdtSymbols = response.data.symbols.filter(symbol => 
            symbol.symbol.endsWith('USDT') && 
            symbol.status // 确保有status字段
          );
          
          logger.debug(`获取到 ${usdtSymbols.length} 个USDT期货交易对状态`);
          return usdtSymbols.map(symbol => ({
            symbol: symbol.symbol,
            status: symbol.status,
            type: 'FUTURES'
          }));
        }

        logger.warn('期货响应数据格式异常，无symbols字段');
        return [];

      } catch (error) {
        logger.error(`币安期货API请求失败 (尝试 ${attempt}/${this.retryCount}): ${error.message}`);
        
        if (attempt < this.retryCount) {
          logger.info(`等待 ${this.retryDelay}ms 后重试...`);
          await new Promise(resolve => setTimeout(resolve, this.retryDelay));
        }
      }
    }

    logger.error('所有重试失败，无法获取币安期货交易对状态');
    return [];
  }

  /**
   * 获取所有USDT交易对状态
   * @returns {Promise<Array>} 所有交易对状态
   */
  async fetchAllSymbolStatus() {
    try {
      logger.info('🔍 开始获取币安USDT交易对状态信息...');
      
      // 并行获取现货和期货数据
      const [spotSymbols, futuresSymbols] = await Promise.allSettled([
        this.fetchSpotExchangeInfo(),
        this.fetchFuturesExchangeInfo()
      ]);

      const spotData = spotSymbols.status === 'fulfilled' ? spotSymbols.value : [];
      const futuresData = futuresSymbols.status === 'fulfilled' ? futuresSymbols.value : [];

      const allSymbols = [...spotData, ...futuresData];
      
      logger.success(`📊 成功获取 ${allSymbols.length} 个USDT交易对状态 (现货: ${spotData.length}, 期货: ${futuresData.length})`);
      return allSymbols;

    } catch (error) {
      logger.error(`获取交易对状态失败: ${error.message}`);
      return [];
    }
  }

  /**
   * 检查状态变化并生成告警
   * @param {Array} currentSymbols 当前交易对状态
   * @returns {Array} 状态变化告警列表
   */
  checkStatusChanges(currentSymbols) {
    const alerts = [];
    const currentTime = new Date();

    for (const symbolInfo of currentSymbols) {
      const key = `${symbolInfo.type}:${symbolInfo.symbol}`;
      const currentStatus = symbolInfo.status;
      const previousStatus = this.previousStatus.get(key);

      // 如果之前有记录且状态发生变化
      if (previousStatus && previousStatus !== currentStatus) {
        // 特别关注从TRADING变为BREAK的情况
        if (previousStatus === 'TRADING' && currentStatus === 'BREAK') {
          alerts.push({
            symbol: symbolInfo.symbol,
            type: symbolInfo.type,
            previousStatus: previousStatus,
            currentStatus: currentStatus,
            changeType: 'CRITICAL', // 关键变化
            timestamp: currentTime.toISOString(),
            message: `🚨 【关键告警】${symbolInfo.type} ${symbolInfo.symbol} 状态从 TRADING 变为 BREAK`
          });
          
          logger.error(`🚨 关键告警: ${symbolInfo.type} ${symbolInfo.symbol} 从 ${previousStatus} 变为 ${currentStatus}`);
        } 
        // 其他状态变化
        else {
          alerts.push({
            symbol: symbolInfo.symbol,
            type: symbolInfo.type,
            previousStatus: previousStatus,
            currentStatus: currentStatus,
            changeType: 'INFO',
            timestamp: currentTime.toISOString(),
            message: `ℹ️  【状态变化】${symbolInfo.type} ${symbolInfo.symbol} 状态从 ${previousStatus} 变为 ${currentStatus}`
          });
          
          logger.info(`📝 状态变化: ${symbolInfo.type} ${symbolInfo.symbol} 从 ${previousStatus} 变为 ${currentStatus}`);
        }
      }

      // 更新状态记录
      this.previousStatus.set(key, currentStatus);
    }

    return alerts;
  }

  /**
   * 执行一次完整的状态检查
   * @returns {Promise<Object>} 检查结果
   */
  async performStatusCheck() {
    const startTime = new Date();
    logger.info('🔍 开始执行币安USDT交易对状态检查...');

    try {
      // 获取当前所有交易对状态
      const currentSymbols = await this.fetchAllSymbolStatus();
      
      if (currentSymbols.length === 0) {
        logger.warn('⚠️  未获取到任何交易对状态数据');
        return {
          success: false,
          message: '未获取到交易对状态数据',
          alerts: [],
          symbolCount: 0,
          duration: Date.now() - startTime
        };
      }

      // 检查状态变化
      const alerts = this.checkStatusChanges(currentSymbols);
      
      // 统计信息
      const statusStats = this.generateStatusStats(currentSymbols);
      
      const duration = Date.now() - startTime;
      
      if (alerts.length > 0) {
        logger.success(`✅ 状态检查完成，发现 ${alerts.length} 个状态变化 (耗时 ${duration}ms)`);
        
        // 统计关键告警数量
        const criticalAlerts = alerts.filter(alert => alert.changeType === 'CRITICAL');
        if (criticalAlerts.length > 0) {
          logger.error(`🚨 发现 ${criticalAlerts.length} 个关键告警！`);
        }
      } else {
        logger.debug(`✅ 状态检查完成，无状态变化 (耗时 ${duration}ms)`);
      }

      return {
        success: true,
        message: `检查完成，监控 ${currentSymbols.length} 个交易对`,
        alerts: alerts,
        symbolCount: currentSymbols.length,
        statusStats: statusStats,
        duration: duration
      };

    } catch (error) {
      const duration = Date.now() - startTime;
      logger.error(`❌ 状态检查失败: ${error.message} (耗时 ${duration}ms)`);
      
      return {
        success: false,
        message: error.message,
        alerts: [],
        symbolCount: 0,
        duration: duration
      };
    }
  }

  /**
   * 生成状态统计信息
   * @param {Array} symbols 交易对列表
   * @returns {Object} 统计信息
   */
  generateStatusStats(symbols) {
    const stats = {
      total: symbols.length,
      byStatus: {},
      byType: {},
      summary: {}
    };

    // 按状态统计
    symbols.forEach(symbol => {
      stats.byStatus[symbol.status] = (stats.byStatus[symbol.status] || 0) + 1;
      stats.byType[symbol.type] = (stats.byType[symbol.type] || 0) + 1;
    });

    // 生成摘要
    stats.summary = {
      trading: stats.byStatus['TRADING'] || 0,
      break: stats.byStatus['BREAK'] || 0,
      others: stats.total - (stats.byStatus['TRADING'] || 0) - (stats.byStatus['BREAK'] || 0),
      spot: stats.byType['SPOT'] || 0,
      futures: stats.byType['FUTURES'] || 0
    };

    return stats;
  }

  /**
   * 获取服务状态信息
   * @returns {Object} 服务状态
   */
  getServiceStatus() {
    return {
      name: 'BinanceStatusService',
      description: 'USDT交易对状态监控服务',
      monitoredSymbols: this.previousStatus.size,
      lastCheck: new Date().toISOString(),
      endpoints: [
        `${this.baseURL}/api/v3/exchangeInfo`,
        `${this.futuresURL}/fapi/v1/exchangeInfo`
      ]
    };
  }

  /**
   * 清空状态历史记录
   */
  clearStatusHistory() {
    this.previousStatus.clear();
    logger.info('📝 已清空状态历史记录');
  }
}

module.exports = BinanceStatusService;
